package com.lsh.oms.core.service.bills.impl;

import com.alibaba.fastjson.JSON;
import com.lsh.oms.core.constant.ReturnCode;
import com.lsh.oms.core.dao.other.OrderShippingDetailMapper;
import com.lsh.oms.core.dao.other.OrderShippingHeadMapper;
import com.lsh.oms.core.exception.BusinessException;
import com.lsh.oms.core.model.bills.OrderDeliverlyVo;
import com.lsh.oms.core.model.order.OrderShippingDetail;
import com.lsh.oms.core.model.order.OrderShippingHeadWithBLOBs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 * @author peter
 * @date 16/11/4
 */
@Service("orderShippingTmsService")
@Slf4j
public class OrderShippingKafkaService extends AbstractKafkaMessageService<OrderDeliverlyVo> {

    @Autowired
    private OrderShippingHeadMapper orderShippingHeadMapper;

    @Autowired
    public OrderShippingDetailMapper orderShippingDetailMapper;

    @Override
    public void doBiz(OrderDeliverlyVo obj) {
        try {
            OrderShippingHeadWithBLOBs head = (OrderShippingHeadWithBLOBs) obj.getOrderShippingHead();
            List<OrderShippingDetail> details = obj.getOrderShippingDetail();

            OrderShippingHeadWithBLOBs cell = orderShippingHeadMapper.selectByshippingOrderId(head.getShippingOrderId());
            log.info("发货单 shippingId: {} db deal start", head.getShippingOrderId());
            if (cell == null) {
                head.setTmsId(head.getId());
                head.setId(null);
                head.setWarehouseData("{}");
                orderShippingHeadMapper.insertSelective(head);

                for (OrderShippingDetail detail : details) {
                    detail.setTmsId(detail.getId());
                    detail.setId(null);
                    orderShippingDetailMapper.insert(detail);
                }
            } else {
                Long headId = head.getId();
                head.setTmsId(headId);
                head.setId(null);
                orderShippingHeadMapper.updateByTmsId(head);
                for (OrderShippingDetail detail : details) {
                    detail.setTmsId(detail.getId());
                    detail.setId(null);
                    orderShippingDetailMapper.updateByTmsId(detail);
                }
            }

            log.info("发货单 shippingId: {} db deal end", head.getShippingOrderId());
        } catch (Exception e) {

            log.error("OrderShippingService ::: Full stack trace follows,:", e);
            throw new BusinessException(ReturnCode.UPDATE_FAIL, "OrderShippingService db exception", e);
        }

    }

    @Override
    public OrderDeliverlyVo parse(String json) throws Exception {
        return JSON.parseObject(json, OrderDeliverlyVo.class);
    }
}
